package lgkj.meicqt20.service;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import lgkj.meicqt20.bean.MessageEvent;
import lgkj.meicqt20.utils.AllKindsOfConstant;
import lgkj.meicqt20.utils.HttpUtils;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * Created by Administrator on 2018/8/1 0001.
 */

public class IoService {
    private static final String TAG = "IoService";
    private Context mContext;
    private BufferedSink mSink;
    private BufferedSource mSource;
    private ExecutorService mExecutorService = null;
    private Socket socket;
    private boolean isConnect;
    private String type;
    private long sureTime = 0;

    public IoService(Context context) {
        this.mContext = context;
        mExecutorService = Executors.newCachedThreadPool();
        mExecutorService.execute(new connectService());  //启动
    }


    private void sendMsg() {
        final String sendMsg = "{\"type\":\"pong\"}";
        Log.i(TAG, "sendMsg: " + isConnect);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
//                if (isConnect) {
                    mExecutorService.execute(new sendService(sendMsg));
//                } else {
//                    mExecutorService.execute(new connectService());
//                }
            }
        }, 0, 3 * 1000);

    }

    private class sendService implements Runnable {
        private String msg;

        sendService(String msg) {
            this.msg = msg;
        }

        @Override
        public void run() {
            try {
                mSink.writeUtf8(this.msg + "\n");
                mSink.flush();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "run: " + e.getMessage());
                isConnect = false;
                mExecutorService.execute(new connectService());
            }
        }
    }

    private class connectService implements Runnable {
        @Override
        public void run() {
            try {
//                socket = new Socket("120.77.213.128", 7272);
                socket = new Socket(AllKindsOfConstant.BASE_IP, 7272);
                isConnect = true;
                mSink = Okio.buffer(Okio.sink(socket));
                mSource = Okio.buffer(Okio.source(socket));
                receiveMsg();
                sendMsg();
            } catch (Exception e) {
                isConnect = false;
                mExecutorService.execute(new connectService());
                Log.e(TAG, ("connectService:" + e.getMessage()));
            }
        }
    }

    private void receiveMsg() {
        try {
            while (true) {
                for (String receiveMsg; (receiveMsg = mSource.readUtf8Line()) != null; ) {
                    Log.d(TAG, "receiveMsg:" + receiveMsg);
                    messageReceived(receiveMsg);
                }
            }
        } catch (IOException e) {
            mExecutorService.execute(new connectService());
            Log.e(TAG, "receiveMsg: " + e.getMessage());
            isConnect = false;
        }
    }

    /**
     * 读取数据
     *
     * @param receive
     */
    private void messageReceived(String receive) {
        try {
            JSONObject object = new JSONObject(receive);
            type = object.getString("type");
            String order = "";
            if (object.has("user") && object.has("tel")) {
                HttpUtils.user = object.optString("user");
                HttpUtils.tel = object.optString("tel");
            }
            switch (type) {
                case "init":
                    bind(object);
                    break;
                case "control":
                    order = object.getString("data");
                    if (order != null) {
                        switch (order) {
                            case "confirm":
                                if ((System.currentTimeMillis() - sureTime) > 1500) {
                                    order = "sure";
                                }
                                sureTime = System.currentTimeMillis();
                                break;
                            case "vol-up":
                                order = "voice_add";
                                break;
                            case "vol-down":
                                order = "voice_less";
                                break;
                        }
                        if (!TextUtils.isEmpty(order)) {
                            Log.d(TAG, "messageReceived: 发送：control下，，，，" + order);
                            mContext.sendBroadcast(new Intent("firstOrder").putExtra("order", order));
                        }
                    }
                    break;
                case "newAdvertlist":
                    Log.e(TAG + ".new", "有新的东西,强制退出!");
                    mContext.sendBroadcast(new Intent("firstOrder").putExtra("order", "newAdvertlist"));
                    break;
                case "leave":
                    mContext.sendBroadcast(new Intent("firstOrder").putExtra("order", "finish"));
                    break;
                case "ping":
                    break;
            }
            EventBus.getDefault().postSticky(new MessageEvent(type));
            Log.d(TAG, "type:" + type + ",order:" + order);
        } catch (JSONException e) {
            Log.i("断开", "断开2");
            e.printStackTrace();
        }
    }

    private void bind(JSONObject object) {
        try {
            if (!TextUtils.isEmpty(object.getString("client_id"))) {
                Map<String, String> params = new HashMap<>();
                params.put("client_id", object.getString("client_id"));
                HttpUtils.getHttp(params, AllKindsOfConstant.bindMac, new HttpUtils.HttpCallBack() {
                    @Override
                    public void successHttp(JSONObject jsonObject, int id) {
                        Log.d(TAG, "successHttp: " + jsonObject.toString());
                    }

                    @Override
                    public void errorHttp(String msg) {
                        Log.e(TAG, "errorHttp: " + msg);
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
